package com.gui.design.factory.simple;

import org.reflections.Reflections;

import java.lang.reflect.Field;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class PhoneFactory {

    private final ConcurrentHashMap<String, IPhone> singletonFactory = new ConcurrentHashMap<>();

    public IPhone createInstance(String type) {
        synchronized (this) {
            IPhone cachePhone = singletonFactory.get(type);
            if (cachePhone != null) {
                return cachePhone;
            }
            Reflections reflections = new Reflections("com.gui.design.factory.simple");
            Set<Class<? extends IPhone>> allSubClassList = reflections.getSubTypesOf(IPhone.class);
            try {
                for (Class<? extends IPhone> classItem : allSubClassList) {
                    Field phoneTypeField = classItem.getDeclaredField("TYPE");
                    Object phoneType = phoneTypeField.get(null);
                    if (phoneType.equals(type)) {
                        IPhone phone = classItem.getConstructor().newInstance();
                        singletonFactory.putIfAbsent(type, phone);
                        return phone;
                    }
                }

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            throw new RuntimeException("玩个蛇皮");
        }
    }
}
